#include <iostream>
#include <string>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>

std::string FormatId(pthread_t tid)
{
    char id[64];
    snprintf(id, sizeof(id), "0x%lx", tid);
    return id;
}

void* routine(void* args)
{
    std::string name = static_cast<const char*>(args);
    pthread_t tid = pthread_self();
    int cnt = 5;
    while(cnt)
    {
        sleep(1);
        std::cout << "I am new thread, my name is " << name  << " My id is " << FormatId(tid) << std::endl;
        cnt--;
    }

    return (void*)100;
}

int main()
{
    pthread_t tid;
    int n = pthread_create(&tid, nullptr, routine, (void*)"thread-1");
    (void)n;
    std::cout << "tid " << FormatId(tid) << std::endl;
    
    void* ret = nullptr;
    pthread_join(tid, &ret);

    std::cout << "return value is " << (long long)ret << std::endl;
    return 0;
}


// void* threadrun(void* args)
// {
//     std::string s = (const char*)args;
//     while(true)
//     {
//         std::cout << "I am new thread, my name is " << s << ".My pid is " << getpid() << std::endl;
//         sleep(1);
//     }

//     return nullptr;
// }

// int main()
// {
//     pthread_t tid;
//     pthread_create(&tid, nullptr, threadrun, (void*)"thread-1");

//     while(true)
//     {
//         std::cout << "I am major thread!!!" << "my pid is " << getpid() << std::endl;
//         sleep(1);
//     }
//     return 0;
// }